#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# 编码 和 解码
'ABC'.encode('ascii')
'中文'.encode('utf-8')
'A'.encode('utf-8')
'中文A*#$'.encode('utf-8')
b'A*#$'.decode('utf-8')
b'\xe4\xb8\xad\xe6\x96\x87A*#$'.decode('utf-8')
 

# match  case 语句
def match_case(x):
    match x:
        case 'A':
            print('A')
        case 'B'|'C':
            print(x)
        case _:
            print('other')

match_case('A')
match_case('C')


age=5
match age:
    case x if x<10:
        print(f'children , age:{x:10.4f}')
    case _:
        print('other age')


args = ['gcc','hello.c','world.c','name.c']
match args:
    case ['gcc']:
        print('gcc:missing source file')
    case ['gcc',file1,*files]:
        fs = ','.join(files)
        print(f'gcc cmopile:{file1},{fs}')



# tuple 
a=(1, [2, 3])
a[1].append(4)
print(a)


# 高阶函数

def num_generator():
    n = 0
    while True:
        n = n + 1
        yield n
def get_numbers(maxNum):
    nums = []
    for n in num_generator():
        if n > maxNum:
            return nums
        else:
            nums.append(n)

print(num_generator)
print(num_generator())

print(get_numbers(5))

def odd_generator(max):
    ng = num_generator()
    while True:
        n = next(ng)
        if n > max:
            return        
        if n % 2 == 1:
            yield n

for x in odd_generator(10):
    print(x)



print(sorted(['bob', 'about', 'Zoo', 'Credit'],key=str.lower))


# 函数参数类型和返回值类型
def f(a:str) -> str:
    return a.upper()
print(f("abc123"))

# 返回函数

def lazy_sum(*args):
    def sum():
        ax = 0
        for n in args:
            ax = ax + n
        return ax
    return sum

f=lazy_sum(1,2,3,4,5)
print(f)
print(f())

# 利用闭包返回一个计数器函数，每次调用它返回递增整数：
def count():
    c=0
    def inc():
        nonlocal c
        c=c+1
        return c
    return inc
inc=count()
for i in range(5):
    print(inc(),end=" ")

def circle():
    fs=[]
    for i in range(1,4):
        def inner():
            return i
        fs.append(inner)
    return fs
f1,f2,f3= circle()
print("\n",f1(),f2(),f3())


def logger():
    def log(func,*args):
        print("before invoke....args:",args)
        func(*args)
        print("after invoke....")
    return log
def test(a,b,*args):
    print("test *args:",*args)
    print(f"invoke .....{a},{b}")

lg = logger()
lg(test,1,2,3,4,5)


# 匿名函数
f = lambda x: x*x
print(f)
print(f(5))
print(list(map(f,[1,2,3,4,5])))
print(list(map(lambda x:x*x,[1,2,3,4,5])))

def build(x,y):
    return lambda a,b:a+b
b = build(3,4)
print(b)
print(b(1,2))

print(list(filter(lambda x:x%2==0, range(1, 20))))

import time


# 装饰器
def time_stat(f):
    def wrapper(*args,**kwargs):
        start = time.time()
        f(*args,**kwargs)
        end = time.time()
        
        print(f"invoke {f.__name__} , time cost:{end-start}")
    return wrapper

@time_stat
def test_time():
    time.sleep(1)

test_time()

def repeat(n):
    def decorator(f):
        def wrapper(*args,**kwargs):
            for i in range(n):
                f(*args,**kwargs)
        return wrapper
    return decorator

@repeat(3)
def test_repeat():
    print("test_repeat...")

test_repeat()

def auth(role):
    def decorator(f):
        roles=['admin','audit','operator']
        def wrapper(*args,**kwargs):
            if role not in roles:
                raise Exception("no permission")    
            f(*args,**kwargs)
        return wrapper
    return decorator

@auth('admin')
def test_auth():
    print("test_auth...")

test_auth()


# type , isinstance 
print('type("abc")==str : ',type("abc")==str)
print('type(abs): ',type(abs))
print('isinstance("abc",str): ',isinstance("abc",str))

class Animal():
    pass
print("type(Animal),",type(Animal))

a = Animal()
print("type(a),",type(a))
